package com.citcc.business.service;

import com.citcc.business.bean.CdzAppUser;
import com.citcc.business.bean.vo.PersonalCenterInformationVO;
import com.citcc.business.mapper.CdzAccountAmountMapper;
import com.citcc.business.mapper.CdzAppUserMapper;
import com.citcc.common.exception.base.BaseException;
import com.citcc.common.utils.DateUtils;
import com.citcc.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by czh on 2019/5/22 0022 16:00
 */
@Service
public class PersonalCenterService {

    @Autowired
    private CdzAppUserMapper appUserMapper;
    @Autowired
    private CdzAccountAmountMapper accountAmountMapper;

    private static final DecimalFormat FORMAT = new DecimalFormat("#,##0.00");

    private Logger log = LoggerFactory.getLogger(PersonalCenterService.class);

    /**
     * 我的资料
     *
     * @param userId
     * @return
     */
    public PersonalCenterInformationVO information(String userId) {

        return Optional.ofNullable(appUserMapper.selectByPrimaryKey(userId)).map(s -> {
            PersonalCenterInformationVO informationVO = new PersonalCenterInformationVO();
            // 总金额
            Optional.ofNullable(accountAmountMapper.selectByUserId(userId)).ifPresent(o -> {
                informationVO.setAmount(FORMAT.format(o.getTotalAmount()));
            });
            // 个人信息
            informationVO.setHeadUrl(s.getHeadImg());
            informationVO.setName(s.getNickNameEncodeValue());
            String phone = s.getPhone();
            if (phone.length() == 11) {
                String before = StringUtils.substring(phone, 0, 3);
                String after = StringUtils.substring(phone, 7);
                informationVO.setPhone(before + "****" + after);
            }

            // 微信信息
            String wechatState = s.getWechatState();
            if (wechatState == null) {
                informationVO.setWechatState("1");
                informationVO.setWechatStateDesc("未绑定");
            } else {
                informationVO.setWechatState(wechatState);
                if (StringUtils.equals("0", wechatState)) {
                    informationVO.setWechatStateDesc("已绑定");
                    informationVO.setWechatHead(s.getWechatHead());
                    informationVO.setWechatName(s.getWechatName());
                    informationVO.setWechatTime(DateUtils.formatDate2Str(1, s.getWechatTime()));
                } else if (StringUtils.equals("1", wechatState)) {
                    informationVO.setWechatStateDesc("未绑定");
                }
            }
            // 支付宝信息
            String alipayState = s.getAlipayState();
            if (alipayState == null) {
                informationVO.setAlipayState("1");
                informationVO.setAlipayStateDesc("未绑定");
            } else {
                informationVO.setAlipayState(alipayState);
                if (StringUtils.equals("0", alipayState)) {
                    informationVO.setAlipayStateDesc("已绑定");
                    informationVO.setAlipayHead(s.getAlipayHead());
                    informationVO.setAlipayName(s.getAlipayName());
                    informationVO.setAlipayTime(DateUtils.formatDate2Str(1, s.getAlipayTime()));
                } else if (StringUtils.equals("1", alipayState)) {
                    informationVO.setAlipayStateDesc("未绑定");
                }
            }
            return informationVO;
        }).orElse(new PersonalCenterInformationVO());
    }

    /**
     * 修改资料
     *
     * @param userId  用户ID
     * @param headUrl 头像
     * @param name    昵称
     */
    public void updateInformation(String userId, String headUrl, String name) {
        CdzAppUser user = new CdzAppUser();
        user.setId(userId);
        if (StringUtils.isNotBlank(headUrl)) user.setHeadImg(headUrl);
        if (StringUtils.isNotBlank(name)) {
            try {
                user.setNickNameEncode(name);
                user.setNickName(URLDecoder.decode(name, "UTF-8"));
            } catch (Exception e) {
                log.error("修改资料解码昵称失败，{}", e.getMessage());
            }
        }
        user.setUpdateTime(new Date());
        appUserMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 微信绑定
     *
     * @param userId
     * @param account
     * @param openid
     * @param name
     * @param headUrl
     */
    public void bindWeChat(String userId, String account, String openid, String name, String headUrl) {

        CdzAppUser cdzAppUser = appUserMapper.selectByPrimaryKey(userId);
        if (cdzAppUser == null || StringUtils.equals("0", cdzAppUser.getWechatState()))
            throw new BaseException("您已绑定过微信");

        CdzAppUser user = new CdzAppUser();
        user.setId(userId);
        user.setWechatAccount(account);
        user.setWechatState("0");
        user.setWechatTime(new Date());
        user.setWechatOpenid(openid);
        user.setWechatHead(headUrl);
        user.setWechatName(name);
        appUserMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 支付宝绑定
     *
     * @param userId
     * @param account
     * @param openid
     * @param name
     * @param headUrl
     */
    public void bindAlipay(String userId, String account, String openid, String name, String headUrl) {

        CdzAppUser cdzAppUser = appUserMapper.selectByPrimaryKey(userId);
        if (cdzAppUser == null || StringUtils.equals("0", cdzAppUser.getAlipayState()))
            throw new BaseException("您已绑定过支付宝");

        CdzAppUser user = new CdzAppUser();
        user.setId(userId);
        user.setAlipayAccount(account);
        user.setAlipayState("0");
        user.setAlipayTime(new Date());
        user.setAlipayOpenid(openid);
        user.setAlipayHead(headUrl);
        user.setAlipayName(name);
        appUserMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 解绑微信或支付宝
     *
     * @param userId
     * @param type
     */
    public void unBind(String userId, String type) {

        CdzAppUser user = appUserMapper.selectByPrimaryKey(userId);

        if (StringUtils.equals("0", type)) {
            // 支付宝
            if (user == null || StringUtils.equals("1", user.getAlipayState()))
                throw new BaseException("您还未绑定支付宝");

            CdzAppUser appUser = new CdzAppUser();
            appUser.setId(userId);
            appUser.setAlipayAccount(null);
            appUser.setAlipayState("1");
            appUser.setAlipayTime(null);
            appUser.setAlipayOpenid(null);
            appUser.setAlipayHead(null);
            appUser.setAlipayName(null);
            appUserMapper.updateByPrimaryKeySelective(appUser);
        } else if (StringUtils.equals("1", type)) {
            // 微信
            if (user == null || StringUtils.equals("1", user.getWechatState()))
                throw new BaseException("您还未绑定微信");

            CdzAppUser appUser = new CdzAppUser();
            appUser.setId(userId);
            appUser.setWechatAccount(null);
            appUser.setWechatState("1");
            appUser.setWechatTime(null);
            appUser.setWechatOpenid(null);
            appUser.setWechatHead(null);
            appUser.setWechatName(null);
            appUserMapper.updateByPrimaryKeySelective(appUser);
        }
    }

    //更新昵称编码
    @Transactional
    public void updateNickNameEncode() {
        try {
            List<CdzAppUser> list = appUserMapper.selectAllList(new CdzAppUser());
            if (null != list && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    CdzAppUser cdzAppUser = list.get(i);
                    //如果不为空 编码
                    if (StringUtils.isNotEmpty(cdzAppUser.getNickName())) {
                        cdzAppUser.setNickNameEncode(URLEncoder.encode(cdzAppUser.getNickName(), "UTF-8"));
                    }
                    appUserMapper.updateByPrimaryKeySelective(cdzAppUser);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}